package com.ruoyi.net.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.XmlUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.net.domain.NetElement;
import com.ruoyi.net.netconf.Device;
import com.ruoyi.net.netconf.util.DeviceManager;
import com.ruoyi.net.service.INetElementService;
import com.ruoyi.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.net.mapper.ElementPortEthMapper;
import com.ruoyi.net.domain.ElementPortEth;
import com.ruoyi.net.service.IElementPortEthService;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * 网元-接口-以太网Service业务层处理
 * 
 * @author net
 * @date 2024-11-17
 */
@Service
public class ElementPortEthServiceImpl implements IElementPortEthService 
{
    @Autowired
    private ElementPortEthMapper elementPortEthMapper;

    @Autowired
    private INetElementService netElementService;

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private DeviceManager deviceManager;

    /**
     * 查询网元-接口-以太网
     * 
     * @param id 网元-接口-以太网主键
     * @return 网元-接口-以太网
     */
    @Override
    public ElementPortEth selectElementPortEthById(String id)
    {
        return elementPortEthMapper.selectElementPortEthById(id);
    }

    /**
     * 查询网元-接口-以太网列表
     * 
     * @param elementPortEth 网元-接口-以太网
     * @return 网元-接口-以太网
     */
    @Override
    public List<ElementPortEth> selectElementPortEthList(ElementPortEth elementPortEth) {
        return elementPortEthMapper.selectElementPortEthList(elementPortEth);
    }

    @Override
    public List<ElementPortEth> init(ElementPortEth elementPortEth)
    {
        // 查找不相同的数据
        List<ElementPortEth> elementPortEths = new ArrayList<>();
        if (StringUtils.isEmpty(elementPortEth.getElementId())) {
            return elementPortEths;
        }

        List<ElementPortEth> readElements = readDevice(elementPortEth);
        List<ElementPortEth> dbElements = elementPortEthMapper.selectElementPortEthList(elementPortEth);
        List<ElementPortEth> uncommonElements = readElements.stream().filter(readBack -> dbElements.stream()
                        .noneMatch(dbElement -> readBack.getPortName().substring(StringUtils.indexOfAny(readBack.getPortName(), "/") - 1)
                                .equalsIgnoreCase(dbElement.getPortName().substring(StringUtils.indexOfAny(dbElement.getPortName(), "/") - 1))))
                .collect(Collectors.toList());
        // 不相同
        for (ElementPortEth uncommonElement : uncommonElements) {
            uncommonElement.setId(IdUtils.simpleUUID());
            uncommonElement.setStatus("1");
            uncommonElement.setElementId(elementPortEth.getElementId());
            uncommonElement.setTerminalName(uncommonElement.getPortName());
            uncommonElement.setCreateBy(SecurityUtils.getUsername());
            uncommonElement.setCreateTime(DateUtils.getNowDate());
            elementPortEthMapper.insertElementPortEth(uncommonElement);
        }
        return elementPortEthMapper.selectElementPortEthList(elementPortEth);
    }

    private List<ElementPortEth> readDevice(ElementPortEth elementPortEth) {
        List<ElementPortEth> elementPortEths = new ArrayList<>();
        StringBuilder xml = new StringBuilder();
        xml.append(
                "<if xmlns=\"http://fiberhome.com/fhnw/yang/interface/fos-interface-common\">" +
                        "    <interfaces>" +
                        "      <interface xmlns:nc=\"urn:ietf:params:xml:ns:netconf:base:1.0\">" +
                        "        <type>ETH-PHY</type>" +
                        "        <enabled>enable</enabled>" + // 主接口
                        "      </interface>" +
                        "    </interfaces>" +
                        "  </if>");
        NetElement netElement = netElementService.getCacheObject(elementPortEth.getElementId());
        Device device = deviceManager.getDevice(netElement.getIp());
        if (device.isConnected()) {
            String rpcReply = deviceManager.getConfig(xml.toString());

            // 解析xml
            NodeList list = XmlUtils.findNetConfXmlNodes(rpcReply, "//interfaces/interface");
            if (list != null && list.getLength() > 0) {
                for (int i = 0; i < list.getLength(); i++) {
                    ElementPortEth entity = new ElementPortEth();
                    entity.setElementId(elementPortEth.getElementId());
                    Node node = list.item(i);
                    // 通过标签名获取节点的值
                    entity.setPortName(XmlUtils.getXmlLabelValue(node, "name"));
                    entity.setTerminalEnable(XmlUtils.getXmlLabelValue(node, "enabled"));
                    entity.setPortDesc(XmlUtils.getXmlLabelValue(node, "description"));
                    Node ethOption = XmlUtils.getXmlLabelNode(node, "eth-option");
                    if (ethOption != null) {
                        entity.setMac(XmlUtils.getXmlLabelValue(ethOption, "mac-address"));
                    }
                    Node ethphyInterface = XmlUtils.getXmlLabelNode(node, "ethphy-interface");
                    if( ethphyInterface != null) {
                        entity.setTerminalSpeedType(XmlUtils.getXmlLabelValue(ethphyInterface, "speed"));
                        entity.setFiberOrCopper(XmlUtils.getXmlLabelValue(ethphyInterface, "port-media-type"));
                        entity.setWorkMode(XmlUtils.getXmlLabelValue(ethphyInterface, "negotiation-enable"));
                    }
                    entity.setTerminalMode(XmlUtils.getXmlLabelValue(node, "transport-layer"));
                    entity.setMbps(XmlUtils.getXmlLabelValue(node, "bandwidth"));
                    Node ipNode = XmlUtils.getXmlLabelNode(node, "ip");
                    if (ipNode !=null) {
                        entity.setMaxFrameLen(XmlUtils.getXmlLabelValue(ipNode, "ipv4-mtu"));
                        Node ipv4AddressListNode = XmlUtils.getXmlLabelNode(ipNode, "ipv4-address-list");
                        if (ipv4AddressListNode != null) {
                            String ip = XmlUtils.getXmlLabelValue(ipv4AddressListNode, "ipv4-address");
                            entity.setIp(StringUtils.isNotEmpty(ip) ? ip.split("/")[0] : "");
                            entity.setMask(StringUtils.isNotEmpty(ip) ? ip.split("/")[1] : "");
                            entity.setIpForm(XmlUtils.getXmlLabelValue(ipv4AddressListNode, "secondry-use"));
                        }
                    }
                    Node vlanNode = XmlUtils.getXmlLabelNode(node, "switched-vlan-cfg");
                    if (vlanNode != null) {
                        Node switchedNode = XmlUtils.getXmlLabelNode(vlanNode, "switched-tpids");
                        entity.setVlan(XmlUtils.getXmlLabelValue(switchedNode, "tpid"));
                    }
                    entity.setStatus("1"); // 从设备读取到的配置，设置状态为未激活
                    elementPortEths.add(entity);
                }
            }
        }
        return elementPortEths;
    }

    /**
     * 新增网元-接口-以太网
     * 
     * @param elementPortEth 网元-接口-以太网
     * @return 结果
     */
    @Override
    public int insertElementPortEth(ElementPortEth elementPortEth)
    {
        String uuid = IdUtils.simpleUUID();
        if (StringUtils.isEmpty(elementPortEth.getId())) {
            elementPortEth.setId(uuid);
        }
        elementPortEth.setCreateBy(SecurityUtils.getUsername());
        elementPortEth.setCreateTime(DateUtils.getNowDate());
        elementPortEth.setUpdateBy(SecurityUtils.getUsername());
        elementPortEth.setUpdateTime(DateUtils.getNowDate());
        return elementPortEthMapper.insertElementPortEth(elementPortEth);
    }

    /**
     * 修改网元-接口-以太网
     * 
     * @param elementPortEth 网元-接口-以太网
     * @return 结果
     */
    @Override
    public int updateElementPortEth(ElementPortEth elementPortEth)
    {
        elementPortEth.setUpdateBy(SecurityUtils.getUsername());
        elementPortEth.setUpdateTime(DateUtils.getNowDate());
        return elementPortEthMapper.updateElementPortEth(elementPortEth);
    }

    /**
     * 批量删除网元-接口-以太网
     * 
     * @param ids 需要删除的网元-接口-以太网主键
     * @return 结果
     */
    @Override
    public int deleteElementPortEthByIds(String[] ids)
    {
        return elementPortEthMapper.deleteElementPortEthByIds(ids);
    }

    /**
     * 删除网元-接口-以太网信息
     * 
     * @param id 网元-接口-以太网主键
     * @return 结果
     */
    @Override
    public int deleteElementPortEthById(String id)
    {
        return elementPortEthMapper.deleteElementPortEthById(id);
    }
}
